import sys

from sanic import Sanic
from blueprints.user_api import user_bp
from apis.upload_file import s3_bp
from apis.get_file import setup_file_download_routes
from utils import result_util
from .config import get_config
from tortoise.contrib.sanic import register_tortoise
from utils.json_util import custom_dumps
from sanic import response
from middleware.error_handler import AppErrorHandler
from sanic_ext import Extend

# 获取环境参数
config_name = sys.argv[1] if len(sys.argv) > 1 else 'default'
# 获取配置文件
Config = get_config(config_name)
# 创建 Sanic 实例
app = Sanic(Config.APP_NAME, dumps=custom_dumps, error_handler=AppErrorHandler())
# 加载配置文件
app.config.update_config(Config)
# 注册 OpenAPI 文档
app.config.OAS_UI_DEFAULT = "swagger"
Extend(app)
# 注册 Blueprint
app.blueprint(user_bp)
app.blueprint(s3_bp)

# 设置oss服务路由
setup_file_download_routes(s3_bp)

# 注册 Tortoise-ORM
register_tortoise(
    app,
    db_url=Config.DATABASE_URL,
    modules={
        "models": ["models"],
    },
    generate_schemas=Config.NAME == 'dev'  # 在开发环境中自动生成表结构
)


# 首页
@app.route('/')
async def index(request):
    return response.json(result_util.ok("Hello World"))


# 启动方法
def start_up():
    app.run(host=Config.HOST, port=Config.PORT, debug=Config.DEBUG, auto_reload=Config.DEBUG)
